#!/bin/sh
# Redhat, Fedora, CentOS, etc. setup script for the SrvrPowerCtrl plugin
# Version 20120419
#

echo 'Setting up SrvrPowerCtrl plugin helper scripts for Redhat, Fedora, etc..'

# dash doesn't like [[ $x =~ $y ]] so use this function instead..
_index()
{
  case $1 in
    *$2*)
    idx=${1%%$2*}
    _INDEX=$(( ${#idx} + 1 )) ;;
    *) _INDEX=0; return 1 ;;
  esac
}


#####################################################################################################
#
# Make sure that this script is running under the correct credentials..
#
#

if [ $(whoami) != "root" ]; then
  echo 'Error: This script needs to be run with root credentials,'
  echo "either via # sudo $0"
  echo 'or under su.'
  exit
fi

#####################################################################################################
#
# Setup variables..
#

#Target dir we're copying scripts into..
TRG_SCRIPT_DIR='/usr/local/sbin'

#Change to the source script directory..
REL_DIR=`readlink -f $0`
SRC_SCRIPT_DIR=`dirname "$REL_DIR"`
PLUGINS_DIR=`echo "$SRC_SCRIPT_DIR" | sed -n -e 's#^\(.*/Plugins\)/.*$#\1#p'`

# SBSVER is used in the utiltiy scripts to find the proper log file..
# Can we assume that LMS is installed off of /var/lib?  That will be the usual case..
SBSVER=`echo "$SRC_SCRIPT_DIR" | sed -n -e 's#^/var/lib/\([^/]*\)/.*$#\1#p'`

if [ -z "$SBSVER" ]; then
  # Just get the 3rd level directory name..
  # Works for both /var/lib/squeezeboxserver and /usr/share/squeezeboxserver
  SBSVER=${SRC_SCRIPT_DIR#/*/*/}
  SBSVER=${SBSVER%%/*}
fi

#SBSUSER='squeezeboxserver'
# Get the service user by looking at the owner of the Plugins dir..
# If LMS is being run from svn code AND if the user hasn't replaced the
# server/Plugins directory to a link to /var/lib/squeezeboxserver/Plugins, then
# this code will fail.
if [ ! -z "$PLUGINS_DIR" ]; then
  SBSUSER=`stat -c %U "$PLUGINS_DIR"`
else
  SBSUSER=`stat -c %U "$0"`
fi

if [ "$SBSUSER" = "root" ]; then
  # LMS can't run under root, so any modifications we'd make to sudoers
  # would be meaningless.
  echo "Error: Cannot setup SrvrPowerCtrl scripts for user 'root'.."
  exit 1
fi

SBSGROUP=`id -ng $SBSUSER`


#####################################################################################################
#
# Start processing..
#

cd "$SRC_SCRIPT_DIR"
CWD_DIR=`pwd`

if [ ! "$SRC_SCRIPT_DIR" = "$CWD_DIR" ]; then
  echo "Error: could not change to directory ${SRC_SCRIPT_DIR}...exiting!"
  echo "${SRC_SCRIPT_DIR} != ${CWD_DIR}"
  exit -1
fi

echo "Installing for ${SBSVER}, user ${SBSUSER}:${SBSGROUP}"
echo "  from ${SRC_SCRIPT_DIR} to ${TRG_SCRIPT_DIR}"


#####################################################################################################
#
# Fixup permissions on our plugin directory.
#
# Are we where we think we need to be??
#
# Because the following permissions fix-up uses relative paths, it is potentially
# dangerious if the script is located in the wrong location, e.g. /home/user.
# So..test that the script is at least located off of a 'squeezecenter' or
# 'squeezeboxserver' dir.  Also..we don't need to fixup permissions if we've
# been installed via the Extension Downloader..
#

CUR_DIR=`pwd`
DIR_TEST2='InstalledPlugins'

for DIR_TEST1 in 'squeezecenter' 'squeezeboxserver'
do
	if ( _index "$CUR_DIR" "$DIR_TEST1" )
	  then
	    if  ( ! _index "$CUR_DIR" "$DIR_TEST2" )
	      then
	        REL_DIR=`readlink -f ../../.`
            if [ "$REL_DIR" != "/" ]; then
	          echo "Fixing up permissions on ${REL_DIR}"
	          chown -R "${SBSUSER}:${SBSGROUP}" "$REL_DIR"
            fi
			break
	    fi
	fi
done

#####################################################################################################
#
# Allow the SC/SBS user to use the 'shutdown' command..
#
#ALLOW='/etc/shutdown.allow'
#FOUNDSTR=`egrep "$SBSUSER" "$ALLOW"`
#if [ -z "$FOUNDSTR" ]; then
#  echo "Adding ${SBSUSER} to ${ALLOW} file.."
#  touch "$ALLOW"
#  echo "$SBSUSER" >>"$ALLOW"
#fi


#####################################################################################################
#
# Make modifications to /etc/sudoers...tell sudo that the user has permissions to run
# these commands without raising a password prompt..
#
#

#File we will be modifying..
SUDOERS='/etc/sudoers'
HOST=`hostname`

MADECHANGES=0

#Make a backup of the sudoers file..
if [ ! -f "${SUDOERS}.org" ]; then
  echo "Backing up up ${SUDOERS} to ${SUDOERS}.org.."
  cp --force $SUDOERS "${SUDOERS}.org"
fi

echo "Backing up up ${SUDOERS} to ${SUDOERS}.bak.."
cp --force $SUDOERS "${SUDOERS}.bak"

#Remove the requiretty directive if present so that the squeezecenter user
# can run commands and scripts without being logged into a console..

EXPR='^\#Defaults[[:blank:]]*requiretty'
FOUNDSTR=`egrep "$EXPR" "$SUDOERS"`

if [ -z "$FOUNDSTR" ]; then
  echo "Disabling ${SUDOERS} requiretty option.."
  sed -i -e 's/\s*Defaults\s*requiretty$/#Defaults    requiretty/' $SUDOERS
  MADECHANGES=1
else
  echo "Option 'requiretty' already disabled.."
fi

#Tack on permission for the lms user to run these commands sans password prompt..
for CMD in "$(which shutdown)" "$(which pm-suspend)" "$(which pm-hibernate)" "$(which pm-powersave)" "$(which crontab) -l"
do

  EXPR="${SBSUSER}.*${CMD}"
  FOUNDSTR=`egrep "$EXPR" "$SUDOERS"`

  if [ -z "$FOUNDSTR" ]; then
    echo "Modifying ${SUDOERS} to allow user ${SBSUSER} to run ${CMD}.."
    #ALL hosts vs specific host..
    echo "%${SBSUSER} ALL=NOPASSWD:${CMD}" >>$SUDOERS
    MADECHANGES=1
  else
    echo "User ${SBSUSER} already has permissions to run ${CMD}.."
  fi

done

#####################################################################################################
#
# Copy our helper scripts to the target dir, fixup logpaths, make them executable, add permissions to sudoers
#
#

for SCRIPTNAME in spc-*.sh
do
  if [ -e "${TRG_SCRIPT_DIR}/${SCRIPTNAME}" ]; then
    mv -f -u "${TRG_SCRIPT_DIR}/${SCRIPTNAME}" "${TRG_SCRIPT_DIR}/${SCRIPTNAME}.bak"
  fi

  echo "Installing ${SCRIPTNAME} to ${TRG_SCRIPT_DIR}"
  cp -f "$SCRIPTNAME" "${TRG_SCRIPT_DIR}/${SCRIPTNAME}"

  # Fixup the reference to the srvrpowerctrl.log file location in the script..
  sed -i -e "s/SBSVERSION/${SBSVER}/g" "${TRG_SCRIPT_DIR}/${SCRIPTNAME}"

  # Fixup permissions
  chown root:root "${TRG_SCRIPT_DIR}/${SCRIPTNAME}"
  chmod 755 "${TRG_SCRIPT_DIR}/${SCRIPTNAME}"

  EXPR="${SBSUSER}.*${TRG_SCRIPT_DIR}/${SCRIPTNAME}"
  FOUNDSTR=`egrep "$EXPR" "$SUDOERS"`

  if [ -z "$FOUNDSTR" ]; then
    echo "Modifying ${SUDOERS} to allow user ${SBSUSER} to run ${TRG_SCRIPT_DIR}/${SCRIPTNAME}"
    #ALL hosts vs specific host..
    echo "%${SBSUSER} ALL=NOPASSWD:${TRG_SCRIPT_DIR}/${SCRIPTNAME}" >>$SUDOERS
    MADECHANGES=1
  else
    echo "User ${SBSUSER} already has permissions to run ${TRG_SCRIPT_DIR}/${SCRIPTNAME}"
  fi
done

#####################################################################################################
#
# Setup finish..
#

if [ $MADECHANGES -gt 0 ]; then
  echo "Done!  Helper scripts installed to ${TRG_SCRIPT_DIR} and ${SUDOERS} has been updated."
  exit 0
else
  echo "No modifications made to ${SUDOERS}"
  exit 1
fi
